/**************************************************************************************
 *                    .::::.
 *                  .::::::::.
 *                 ::::::::::: 
 *             ..:::::::::::'
 *           '::::::::::::'
 *             .::::::::::
 *        '::::::::::::::..
 *             ..::::::::::::.
 *           ``::::::::::::::::  在人间，有谁活着不像是一场炼狱 
 *            ::::``:::::::::'        .:::.
 *           ::::'   ':::::'       .::::::::.
 *         .::::'      ::::     .:::::::'::::.
 *        .:::'       :::::  .:::::::::' ':::::.
 *       .::'        :::::.:::::::::'      ':::::.
 *      .::'         ::::::::::::::'         ``::::.
 *  ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 *                    '.:::::'                    ':'````..
 * ----------------- 网络请求类
 * ----------------  yaohuitao@100tal.com
 * ----------------- 20180906
 * ヽ｀、ヽ｀｀、ヽ｀ヽ｀、、ヽ ｀ヽ 、ヽ｀🌙｀ヽヽ｀ヽ、ヽ｀ヽ｀、ヽ｀｀、ヽ 
 * 、｀｀、 ｀、ヽ｀ 、、ヽ｀｀、ヽ、｀｀、、ヽ｀｀、 、ヽヽ｀、｀、、ヽヽ、｀｀
 * 、 、 ヽ｀、ヽ｀｀、ヽ｀ヽ｀、、ヽ ｀ヽ 、ヽ｀｀ヽ、💃｀ヽ🏃、、🚶｀🚶🚶ヽ｀、
***************************************************************************************/
class RequestFn {
    public constructor() {

    }
    /**
     * 获取实例
     */
    static RequestFn: RequestFn
    static get instance() {
        if (!this.RequestFn) {
            this.RequestFn = new RequestFn()
        }
        return this.RequestFn
    }

    /**
     * 静态公共数据
     * @req_from 接口请求1
     * @auth_key 接口请求auth_key
    */
    public static base = {
        apiHosts: "http://shop.mobby.cn/",
        //apiHosts:"http://shop.mobbyxt.com/",
        //apiHosts:"http://mobby.shop/",
        req_from: "1",
        auth_key: "di2f83sk3c9npaz38cmzcl834d9d21ka",
        area: __global.query_area,
        stu_uid: __global.query_uid,//测试用帐号
        version: __global.version,  //版本号，防缓存
        sysTime: ""
    }

    /**
     * 生成Token***
     * str=RequestFn.base.req_from+"&"+RequestFn.base.auth_key+"@"+date("Y-m-d");
     * 如 md5(“1&auth_key@2016-09-06”);
    */
    public creatToken() {
        //获取当前时间
        var date = new Date();
        var year = date.getFullYear();
        var month: number = date.getMonth() + 1;
        var monthstr: string = "" + month;
        if (month < 10) {
            monthstr = "0" + monthstr;
        }
        var day: number = date.getDate();
        var daystr = "" + day;
        if (day < 10) {
            daystr = "0" + daystr;
        }
        var dayString = year + "-" + monthstr + "-" + daystr;
        //let dayString=__global.window.sysTime;
        var token: string = "";
        var strmd5 = "1&" + RequestFn.base.auth_key + "@" + dayString;
        var tokenMd5: string = new md5().hex_md5(strmd5);
        return tokenMd5;
    }

    //***转为url请求字符串***
    public creatJsonUrl(obj) {
        var tokenstr = this.creatToken();
        var resultUrl = "token=" + tokenstr + "&req_from=" + RequestFn.base.req_from + "&area=" + RequestFn.base.area + "&stu_uid=" + RequestFn.base.stu_uid;
        if (obj) {
            if (typeof (obj) == "string") {
                //为字符串类型时直接拼接
                resultUrl = resultUrl + "&" + obj;
            } else if (typeof (obj) == "object") {
                var objstr = "";
                for (var v in obj) {
                    objstr += "&" + v + "=" + obj[v];
                }
                resultUrl = resultUrl + objstr;
            }
        }
        return resultUrl;
    }

    /**
     * Ajax请求类
     * @url 如果不带前缀，则默认为为shop域名下，自动拼上http前缀。如果其他域名（需http或https开头），则不拼前缀
     * @successFn 请求成功回调
     * @errorFn 请求失败回调 
    */
    public Ajax(reqUrl, successFn?: Function, errorFn?: Function) {
        let requestUrl = reqUrl;
        //外部域名
        if (reqUrl.indexOf("http") != 0) {
            requestUrl = RequestFn.base.apiHosts + reqUrl;
        }

        var paramsStr = this.creatJsonUrl(""); //默认不带参数
        var loader: egret.URLLoader = new egret.URLLoader();
        var request: egret.URLRequest = new egret.URLRequest(requestUrl);
        request.method = egret.URLRequestMethod.POST;
        request.data = new egret.URLVariables(paramsStr);
        loader.load(request);
        loader.addEventListener(egret.Event.COMPLETE, onPostComplete, this);
        loader.addEventListener(egret.IOErrorEvent.IO_ERROR, onPostIOError, this);

        function onPostComplete(event: egret.Event): void {
            //隐藏加载
            var loader: egret.URLLoader = <egret.URLLoader>event.target;
            var data: egret.URLVariables = loader.data.toString();
            var res = JSON.parse(data.toString())
            if (res.flag == 1) {
                if (successFn) {
                    successFn(res.data);
                }
            } else {
                if (errorFn) {
                    errorFn();
                    //加提示

                }
            }
        }

        function onPostIOError(event: egret.IOErrorEvent): void {
            console.log("post error : " + event);
            if (errorFn) {
                errorFn();
            }
        }
    }
}